package client.gui;

import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import client.control.ClientControl;

import common.IServer;

import entity.Constants;

public class ConnectPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7160736202567908461L;
	
	public ClientControl cc;
	public APoolPanel appanel;
	
	private TextField tfId, tfName;
	
	public ConnectPanel() {
		
		this.setSize(Constants.PANEL_CONNECT_WIDTH, Constants.PANEL_CONNECT_HEIGHT);
		this.setLayout(new FlowLayout(FlowLayout.CENTER));
		setBorder(BorderFactory.createBevelBorder(0, Color.LIGHT_GRAY, Color.DARK_GRAY));
		
		initComponents();
	}
	
	private void initComponents() {
		Label lbId = new Label("ID");
		tfName = new TextField();
		tfId = new TextField();
		Button btnConnect = new Button("Connect");
		
		tfId.setSize(50, 20);
		tfName.setSize(50, 20);
		
		this.add(lbId);
		this.add(tfName);
		this.add(tfId);
		this.add(btnConnect);
		
		btnConnect.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				handleListener();
			}
		});
	}
	
	private void handleListener() {
		
		this.setVisible(false);
		appanel.setVisible(true);
		
		//connect to server
		try {
			System.setSecurityManager(new RMISecurityManager());
			
			IServer serverCtrl = (IServer) Naming.lookup("rmi://127.0.0.1:1099/server");
			System.out.println("connection is successful");
			
			cc.name = tfName.getText();
			cc.id = Integer.parseInt(tfId.getText());
			serverCtrl.connect(cc);
			
		}
		catch(Exception e) {
			
		}
	}
}
